package com.wzz.controller;//...

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Objects;

@Slf4j
@Controller
public  class FaviconController {
 
    @GetMapping("favicon.ico")
    void returnNoFavicon(HttpServletResponse response) {
        String path = this.getClass().getClassLoader().getResource("").getPath();
//        String prefix = "data:image/vnd.microsoft.icon;base64,";
        extracted(response,"favicon.ico",path+"/"+"static/favicon.ico");
    }

    public static void extracted(HttpServletResponse response, String fileName,String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("下载文件不存在");
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buff = new byte[4096];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            os.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }


    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath
     */

    private  String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(Objects.requireNonNull(data));
    }
}

//...
